package com.my.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.GradeClass;
import com.my.service.GradeClassService;
import com.my.util.Rest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("gradeClass")
public class GradeClassController {

    @Autowired
    private GradeClassService service;

    @GetMapping("list")
    public String list() {
        return "gradeClass/list";
    }

    @GetMapping("getList")
    @ResponseBody
    public Rest getList() {
        return Rest.ok().setData("list", service.list());
    }

    @GetMapping("getClassByGrade")
    @ResponseBody
    public Rest getClassByGrade(Long id) {
        return Rest.ok().setData("list", service.list(new QueryWrapper<GradeClass>().eq("parent_id", id)));
    }

    @GetMapping("edit")
    public String edit(Model model, Long id) {
        model.addAttribute("gradeList", service.list(new QueryWrapper<GradeClass>().eq("deep", 1)));
        if(id != null) {
            model.addAttribute("gradeClass", service.getById(id));
        }
        return "gradeClass/edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public Rest edit(GradeClass gradeClass) {
        if(gradeClass.getId() == null ? service.save(gradeClass): service.updateById(gradeClass)) {
            return Rest.ok("保存成功！");
        }
        return Rest.err("保存失败！");
    }

    @PostMapping("del")
    @ResponseBody
    public Rest del(Long id) {
        int count = service.count(new QueryWrapper<GradeClass>().eq("parent_id", id));
        if(count > 0) {
            return Rest.err("该年级下还有班级，无法删除");
        }
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

}
